<template>
  <avue-draggable
    ref="draggable"
    :step="step"
    :width="widgetsWidth"
    :height="widgetsHeight"
    :disabled="widgetDisabled"
    :left="widgetsLeft"
    :top="widgetsTop"
    :index="index"
    @blur="handleBlur"
  >
    <component :is="currentComponent" :widget-index="index" :widgetOptions="widgetData.options" />
  </avue-draggable>
</template>

<script setup lang="ts">
import { ref, computed, toRefs } from 'vue'
import { componentMap } from './widgetMap'

// props 解构
const props = defineProps<{
  index: number
  widgetData: any
  step: number
}>()

const emit = defineEmits(['onActivated'])

// 解构 props
const { widgetData } = toRefs(props)

// 根据 currentType 选择正确的组件
const currentComponent = computed(() => {
  return componentMap[widgetData.value.code]
})

// ref
const draggable = ref<any>(null)

// computed
const widgetsWidth = computed(() => widgetData.value.options.position.width)
const widgetsHeight = computed(() => widgetData.value.options.position.height)
const widgetsLeft = computed(() => widgetData.value.options.position.left)
const widgetsTop = computed(() => widgetData.value.options.position.top)
const widgetDisabled = computed(() => widgetData.value.options.position.disabled || false)

const handleBlur = ({ index, left, top, width, height }) => {
  if (
    index !== props.index ||
    left !== widgetsLeft.value ||
    top !== widgetsTop.value ||
    width !== widgetsWidth.value ||
    height !== widgetsHeight.value
  ) {
    emit('onActivated', { index, left, top, width, height })
    draggable.value.setActive?.(true)
  }
}
</script>

<style scoped lang="scss">
.vue-draggalbe {
  position: absolute;
}
.widget-active {
  cursor: move;
  border: 1px dashed #09f;
  background-color: rgba(115, 170, 229, 0.5);
}
.avue-draggable {
  padding: 0 !important;
  :deep(.avue-draggable__item) {
    width: 100%;
    height: 100%;
  }
}
</style>
